#pragma once

#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "Log.hpp"

enum{
    SOCKET_ERR = 1,
    SOCKET_BIND_ERR,
    LISTEN_ERR,
    ACCEPT_ERR,
};

const int backlog = 10;

class Sock
{
public:
    Sock() {}
    ~Sock() {}

    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(_sockfd < 0)
        {
            lg(Fatal, "socket create failed! errno: %d, strerror: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }   

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        
        if(bind(_sockfd, (struct sockaddr*)&local, (socklen_t)sizeof(local)) < 0)
        {
            lg(Fatal, "socket bind failed! errno: %d, strerror: %s", errno, strerror(errno));
            exit(SOCKET_BIND_ERR);
        }
    }   

    void Listen()
    {
        if(listen(_sockfd, backlog) < 0)
        {
            lg(Fatal, "socket listen failed! errno: %d, strerror: %s", errno, strerror(errno));
            exit(LISTEN_ERR);
        }
    } 

    int Accept(std::string* clientip, uint16_t* clientport)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int newfd = accept(_sockfd, (struct sockaddr*)&client, &len);
        if(newfd < 0)
        {
            lg(Warning, "socket accept failed! errno: %d, strerror: %s", errno, strerror(errno));
            return -1;
        }
        char ipstr[32];
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));
        *clientip = ipstr;
        *clientport = ntohs(client.sin_port);

        return newfd;
    }

    bool Connect(const std::string ip, const uint16_t port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &peer.sin_addr);

        int n = connect(_sockfd, (struct sockaddr*)&peer, sizeof(peer));    
        if(n < 0)
        {
            std::cerr << "connect failed!" << std::endl;
            return false;
        }
        return true;
    }

    int Fd() { return _sockfd; }
    void Close() { close(_sockfd); }
private:
    int _sockfd;
};

